import { defineComponent, computed, inject } from 'vue';
import lodash from 'lodash';
import './cardConfig.scss';

import city from '@/assets/js/city.js';
import plusIcon from '../../detail/components/FormConfigComponents/icon/plus-icon.svg';
import { uploadFile2 } from '@/api/common';

export default defineComponent({
    name: 'PreviewForm',
    props: {
        controlCardColumns: {
            type: Array,
            default: () => []
        },
        formData: {
            type: Object,
            default: () => ({})
        },
        activity_data: {
            type: Object,
            default: () => ({})
        },
        readOnly: Boolean,
        coverImage: String,
    },

    setup(this, props, ctx: any) {
        const formDataModel: any = inject('formDataModel');
        // 上传文件
        const doUpload = async (file: any) => {
            const params = {
                file: file.file,
                fileName: file.file.name
            };
            const res: any = await uploadFile2(params);
            return res;
        };
        /* 渲染控件列表 */
        const renderCarouselByRules = (El: any, v: any) => {
            const rules = v.rules_list;
            if (rules?.length) {
                // for (const iterator of rules) {
                //     for (const valList of iterator.related_value) {
                //         if (formDataModel[iterator.related_key] === valList) {
                //             return El;
                //         }
                //     }
                // }
                const hasRelated = rules.some(iterator => {
                    if (lodash.isArray(formDataModel[iterator.related_key])) {
                        return iterator?.related_value?.some(rItem =>
                            formDataModel[iterator.related_key].includes(rItem)
                        );
                    }
                    return iterator?.related_value?.some(rItem => formDataModel[iterator.related_key] === rItem);
                });
                if (!hasRelated) {
                    delete formDataModel[v.key];
                } else {
                    return El;
                }
            } else {
                return El;
            }
        };
        const renderEmpty = () => {
            return <div class="preview-card-empty">请点击左侧按钮添加控件～</div>;
        };
        const renderShowContentList = (columns: any) => {
            return (
                // 收集表表单
                <div class="preview-card-list">
                    <div class="preview-card-item">
                        {props.activity_data.activity_name && (
                            <div class="preview-card-item__title">{props.activity_data.activity_name}</div>
                        )}
                        {props.activity_data.form_desc && (
                            <el-input
                                class="form-config-textarea"
                                type="textarea"
                                autosize
                                v-model={props.activity_data.form_desc}
                                placeholder=""
                                readonly={true}
                                resize="none"
                            />
                        )}
                        {props.activity_data?.period_type === 2 && (
                            <div class="form-config-endtime">截止时间：{props.activity_data?.endTime}</div>
                        )}
                    </div>
                    {columns.map((v: any, i: number) => {
                        return renderCarouselByRules(
                            <div class="preview-card-item" key={v.id}>
                                <div class="preview-card-item__title">
                                    <div>
                                        <span class="preview-card-item__title__index">
                                            <span class="is-require">{v.is_require ? '*' : ''}</span>
                                            {`${i + 1}`.padStart(2, '0')}
                                        </span>
                                        {v.form_change_title || v.form_title}
                                    </div>
                                </div>
                                <div class="preview-card-item__desc">
                                    <div>{v.form_desc} </div>
                                </div>
                                <div class="preview-card-item__input">{renderControlInput(v)}</div>
                            </div>,
                            v
                        );
                    })}
                </div>
            );
        };

        // 上传图片控件url
        const doUploadCarousel = async (file: any, v: any) => {
            const res = await doUpload(file);
            formDataModel[v.key].splice(0, formDataModel[v.key].length, res);
        };
        // 渲染控件卡片
        const renderControlInput = (v: any) => {
            /** 这里是参数的约定，以防止dom混乱看起来有点复杂
             * v @param 这个是当前选项卡的对象
             * item @param 如果当前选项卡是多选，或者下拉，item是属于options_list里的每一项
             * picUrl @param 如果当前选项卡是图片，picUrl是属于picture_url里的每一项
             */
            switch (v.type) {
                case 'textbox':
                case 'mobile':
                case 'email':
                    return (
                        <el-input
                            v-model={formDataModel[v.key]}
                            placeholder={v.form_placeholder}
                            readonly={props.readOnly}></el-input>
                    );
                case 'select':
                    return (
                        <>
                            <el-select
                                v-model={formDataModel[v.key]}
                                placeholder={v.form_placeholder}
                                readonly={props.readOnly}>
                                {v.options_list?.map?.((item: any, op_index: number) => {
                                    return <el-option key={item.value} label={item.value} value={item.value} />;
                                })}
                            </el-select>
                        </>
                    );
                case 'radio':
                    return (
                        <>
                            <el-radio-group v-model={formDataModel[v.key]} readonly={props.readOnly}>
                                {v.options_list?.map?.((item: any, op_index: number) => {
                                    return (
                                        <el-radio key={item.value} label={item.value}>
                                            {item.value}
                                        </el-radio>
                                    );
                                })}
                            </el-radio-group>
                        </>
                    );
                case 'muti_select':
                    return (
                        <>
                            <el-checkbox-group v-model={formDataModel[v.key]} readonly={props.readOnly}>
                                {v.options_list?.map?.((item: any, op_index: number) => {
                                    return <el-checkbox key={item.value} label={item.value} value={item.value} />;
                                })}
                            </el-checkbox-group>
                        </>
                    );
                case 'textarea':
                    return (
                        <el-input
                            v-model={formDataModel[v.key]}
                            type="textarea"
                            rows={5}
                            placeholder={v.form_placeholder}
                            readonly={props.readOnly}></el-input>
                    );
                case 'pca':
                    return (
                        <>
                            <el-cascader
                                v-model={formDataModel[v.key]}
                                options={city}
                                props={{
                                    expandTrigger: 'hover',
                                    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
                                    emitPath: false,
                                    label: 'name',
                                    value: 'id'
                                }}
                                placeholder="省/市/区（县）"
                                readonly={props.readOnly}
                            />
                        </>
                    );
                case 'date':
                    return (
                        <el-date-picker
                            v-model={formDataModel[v.key]}
                            type="date"
                            placeholder={v.form_placeholder}
                            readonly={props.readOnly}
                        />
                    );
                case 'picture':
                    return (
                        <>
                            <el-upload
                                v-model:file-list={formDataModel[v.key]}
                                class="preview-card-item__upload"
                                list-type="picture-card"
                                accept=".jpg,.png.,gif,.JPEG"
                                http-request={(file: any) => doUploadCarousel(file, v)}
                                show-file-list={false}>
                                {formDataModel[v.key].length ? (
                                    <div class="share_file">
                                        <img src={formDataModel[v.key][0].url} />
                                    </div>
                                ) : (
                                    <div>
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                        <div>点击上传</div>
                                    </div>
                                )}
                            </el-upload>
                            <div class="upload_tip">建议图片大小不超过10M</div>
                        </>
                    );
                case 'carousel':
                    return (
                        <>
                            {v.picture_url.length === 1 ? (
                                <img class="preview-card-item__carousel_img" src={v.picture_url[0]} alt="" />
                            ) : (
                                <el-carousel interval={2000} height="164px" arrow="never">
                                    {v.picture_url?.map((picUrl: any) => {
                                        return (
                                            <el-carousel-item>
                                                <img class="preview-card-item__carousel_img" src={picUrl} alt="" />
                                            </el-carousel-item>
                                        );
                                    })}
                                </el-carousel>
                            )}
                        </>
                    );
                case 'rate':
                    return (
                        <>
                            <el-rate
                                v-model={formDataModel[v.key]}
                                colors={new Array(3).fill('#FF6B00')}
                                class="preview-card-item__rate"
                                readonly={props.readOnly}
                            />
                        </>
                    );

                default:
                    return <div>没有找到该控件呢～</div>;
            }
        };

        const setState: any = inject('setState');

        return () => (
            <article class="preview-card-form preview-card-form-clone">
                <img src={props.coverImage} />
                {renderShowContentList(props.controlCardColumns)}
                {props.controlCardColumns.length ? (
                    <div class="preview_submit">
                        <el-button type="primary" onClick={setState}>
                            提交
                        </el-button>
                    </div>
                ) : (
                    <div />
                )}
            </article>
        );
    }
});
